<template>
  <div>
    <!-- 项目接收信息 -->
    <div class="desc-item" v-if="isShowApprovalOperation('first')">
      <div class="form-item">项目接收信息</div>
      <DynamicDescription
        ref="dynamicDescription"
        :descriptions="projectTransferDetails.projectAcceptDesc"
        :descriptForm="projectTransferDetails.projectAcceptForm"
        :readOnly="!isShowApprovalOperation('first')"
        :column="1"
        :userSelectDialogProps="thirdManagerProps"
        @handleSelectedUser="handleSelectedUser"
      />
      <div v-if="isShowApprovalOperation('first')">
        <div class="form-item">审批信息</div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData"
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="danger"
            size="default"
            @click="approvalTransferProcess('refuse', 'accepter')"
          >驳回</el-button>
          <el-button
            type="primary"
            size="default"
            @click="approvalTransferProcess('agree', 'accepter')"
          >同意</el-button>
        </div>
      </div>
    </div>
    <!-- 选择交付经理 -->
    <div class="desc-item" v-if="taskName !== '项目交底人审批'">
      <div class="form-item">项目关键人</div>
      <DynamicDescription
        ref="dynamicDescription"
        :descriptions="projectTransferDetails.projectManagerDesc"
        :descriptForm="projectTransferDetails.projectManagerForm"
        :readOnly="!isShowApprovalOperation('second')"
        :column="1"
        :userSelectDialogProps="managerProps"
        @handleSelectedUser="handleSelectedUser"
      />
      <DynamicDescription
        ref="dynamicDescription2"
        :descriptions="projectTransferDetails.maintenanceManagerDesc"
        :descriptForm="projectTransferDetails.maintenanceManagerForm"
        :readOnly="!isShowApprovalOperation('second')"
        :column="1"
        :userSelectDialogProps="maintenanceManagerProps"
        @handleSelectedUser="handleSelectedUser2"
      />
      <div v-if="isShowApprovalOperation('second')">
        <div class="form-item">审批信息</div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData" 
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="danger"
            size="default"
            @click="approvalTransferProcess('refuse', 'thirdManager')"
          >驳回</el-button>
          <el-button
            type="primary"
            size="default"
            @click="approvalTransferProcess('agree', 'thirdManager')"
          >同意</el-button>
        </div>
      </div>
    </div>
    <!-- 项目流程信息 -->
    <div class="desc-item" v-if="!['项目交底人审批', '三级经理审批'].includes(taskName)">
      <div class="form-item">项目流程信息</div>
      <DynamicDescription
        ref="dynamicDescription"
        :descriptions="projectTransferDetails.projectProcessDescs"
        :descriptForm="projectTransferDetails.projectProcessForm"
        :readOnly="!isShowApprovalOperation('third')"
        :column="2"
      />
      <div v-if="projectFiles[processStageName].length > 0">
        <div class="table-title">上传附件</div>
        <FilesUpload
          ref="filesUploadRef"
          :fileTypes="projectFiles[processStageName]"
          :projectInfo="projectInfo"
          :readOnly="!isShowApprovalOperation('third')"
          @getProjectFilesInfo="$emit('getProjectFilesInfo')"
        />
      </div>
      <div v-if="isShowApprovalOperation('third')">
        <div class="form-item">审批信息</div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData" 
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="danger"
            size="default"
            @click="approvalTransferProcess('refuse', 'manager')"
          >驳回</el-button>
          <el-button
            type="primary"
            size="default"
            @click="approvalTransferProcess('agree', 'manager')"
          >同意</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import DynamicDescription from '@/views/project/projectDetails/components/DynamicDescription.vue'
import FilesUpload from '@/views/project/projectDetails/components//FilesUpload.vue';
import { ref, toRefs } from 'vue'
import {agreeAccepterProcess} from "@/api/project/bpm";
import ApprovalOpinion from '@/views/project/components/ApprovalOpinion.vue';

// emit事件合集
const emit = defineEmits(['getApprovalProcess', 'getProjectInfo', 'getProjectFilesInfo']);

// Props传值
const props = defineProps({
  isShowApprovalOperation: Function,
  projectInfo: Object,
  projectTransferDetails: Object,
  processStageName: String,
  taskName: String,
  role: String,
  processList: Array,
  projectFiles: Object
})
const { isShowApprovalOperation, projectInfo, projectTransferDetails, processStageName, taskName, role, processList } = toRefs(props);
const thirdManagerProps = ref({
  role: "thirdManager",
  execute_region: projectInfo.value.execute_region,
})

const managerProps = ref({
  role: "manager",
  execute_region: projectInfo.value.execute_region,
})

const maintenanceManagerProps = ref({
  role: 'maintenanceManager',
  execute_region: projectInfo.value.execute_region
})

// 已选中人员对象
let selectedUserList = reactive([])
let selectedUserList2 = reactive([])

// 动态详情组件ref对象
const dynamicDescription = ref()
const dynamicDescription2 = ref()
// 审批意见
const approvalOpinionData = ref('同意')
const approvalOpinionRef = ref()
// 创建对文件上传子组件的引用
const filesUploadRef = ref(null);

const approvalTransferProcess = async (result, currentRole) => {
  try {
    if (result === 'agree') {
      if (dynamicDescription2.value) {
        await Promise.all([
          dynamicDescription.value.validateForm(),
          dynamicDescription2.value.validateForm(),
          approvalOpinionRef.value.validateForm()
        ])
      } else {
        await Promise.all([
          dynamicDescription.value.validateForm(),
          approvalOpinionRef.value.validateForm()
        ])
      }
      if (filesUploadRef.value && !filesUploadRef.value?.validateFiles()) {
        return;
      }
    } else {
      await approvalOpinionRef.value.validateForm()
    }

    // 表单验证通过，执行提交逻辑
    ElMessageBox.confirm(`是否${result === 'agree' ? '同意' : '驳回'}该流程单？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const approvalFormData = dynamicDescription.value.getFormData()
      
      if (result === 'agree') {
        const aggreeData = {
          process_instance_id: processList.value[0].process_instance_id,
          assigned_user_ids: selectedUserList.map(user => user.id),
          task_id: processList.value[0].id,
          reason: approvalOpinionData.value || '同意',
          copy_user_ids: [],
          variables: {}
        }
        
        // await BpmApi.agreeProcess(aggreeData).then(() => {
        //   emit('getApprovalProcess')
        // })
        if (currentRole === 'accepter') {
          await BpmApi.agreeAccepterProcess(aggreeData).then(() => {
            emit('getApprovalProcess')
          })
          projectInfo.value.construction_department_manager = approvalFormData.construction_department_manager
          projectInfo.value.construction_department_manager_id = selectedUserList[0].id
        } else if (currentRole === 'thirdManager') {
          await BpmApi.agreeProcess(aggreeData).then(() => {
            emit('getApprovalProcess')
          })
          projectInfo.value.construction_project_manager = selectedUserList[0].nickname
          projectInfo.value.construction_project_manager_id = selectedUserList[0].id
          projectInfo.value.maintenance_manager = selectedUserList2[0].nickname
          projectInfo.value.maintenance_manager_id = selectedUserList2[0].id
        } else if (currentRole === 'manager') {
          await BpmApi.agreeProcess(aggreeData).then(() => {
            emit('getApprovalProcess')
          })
          projectInfo.value = Object.assign(projectInfo.value, approvalFormData)
        }
        await KmsApi.addProjectInfo(projectInfo.value).then(() => {
          emit('getProjectInfo')
        })
      } else if (result === 'refuse') {
        const refuseData = {
          process_instance_id: processList.value[0].process_instance_id,
          task_id: processList.value[0].id,
          reason: approvalOpinionData.value || '不同意'
        }
        await BpmApi.refuseProcess(refuseData, currentRole).then(() => {
          emit('getApprovalProcess')
        })
      }
      ElMessage({
        type: 'success',
        message: '提交成功'
      })
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '请按照格式要求填写信息'
    })
  }
}

const handleSelectedUser = ({ userList, fieldName }) => {
  selectedUserList = userList
}

const handleSelectedUser2 = ({ userList, fieldName }) => {
  selectedUserList2 = userList
}

</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

</style>
